package com.ldy.core.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.exception.MagicLoginException;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;
import org.ssssssss.magicapi.utils.MD5Utils;

import com.ldy.core.entity.BaseUser;
import com.ldy.core.service.BaseUserService;
import com.ldy.core.util.MySession;

/**
 * 自定义用户名密码登录
 */
@Component  //注入到Spring容器中
public class CustomAuthorizationInterceptor implements AuthorizationInterceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(CustomAuthorizationInterceptor.class);

	@Autowired
	private BaseUserService userService;
	
	/**
     * 配置是否需要登录
	 */
	@Override
	public boolean requireLogin() {
		return true;
	}

	/**
     * 根据Token获取User
	 */
	@Override
	public MagicUser getUserByToken(String token) throws MagicLoginException {
		logger.info("验证token: {}", token);
        // 如果还是没有token,则抛异常
        if (StringUtils.isEmpty(token)) {
           throw new MagicLoginException(Constant.TOKEN_NULL);
        }

        // 查询token信息
        LoginUser loginUser = MySession.get(token);
        if (null == loginUser) {
        	throw new MagicLoginException(Constant.TOKEN_ERROR);
        }
        // 延长token时效
        MySession.reset(token, loginUser);
        return new MagicUser(loginUser.getId(), loginUser.getUsername(), token);
	}

	@Override
	public MagicUser login(String username, String password) throws MagicLoginException {
		logger.info("登录magic: username： {}； password: {}", username, password);
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) ) {
			throw new MagicLoginException("用户名或密码不正确");
		}
		if (!"admin".equals(username)) {
			throw new MagicLoginException("用户名或密码不正确");
		}
		BaseUser user = userService.login(username, MD5Utils.encrypt(password));
		String token = MySession.add(user);
		return  new MagicUser(user.getId(), user.getUsername(), token);
	}

}